<script setup lang="ts">
  import { ref, defineEmits, computed, watch, onMounted, nextTick } from 'vue';
  import { useBooleanStore } from '@/store';
  import { getUserJob } from '@/utils/auth';
  import { Notification } from '@arco-design/web-vue';
  import {
    searchPlanByItemTypeZ,
    searchBZJCode,
    bzjScanRecive,
  } from '@/api/material-receipt';

  const emit = defineEmits(['updateArray']);
  const booleanStore = useBooleanStore();
  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  const scanInput = ref<any>('');
  // 表单查询数据

  const itemCode = ref<string>('');
  const qualityNumber = ref<string>('');

  const pageSize = ref<number>(10);
  const pageNumber = ref<number>(1);
  const current = ref<number>(1);
  const description = ref<string>('待完成');
  const description2 = ref<string>('待完成');
  const scanCode = ref<string>('');
  const scanCodeType = ref<string>('Y');
  // 操作码俩次确认
  const isConfirm = ref<boolean>(false);
  const disabled = ref<boolean>(false);
  // 存储移交成功的数据
  const scanDataList = ref<any[]>([]);
  const barcode = ref<string>('');

  const inputTableData = ref<any[]>([]);
  // 发送搜索数据
  const flowQueryData = ref({
    itemCode: computed(() => itemCode.value),
    qualityNumber: computed(() => qualityNumber.value),
    pageSize: computed(() => pageSize.value),
    currentPage: computed(() => pageNumber.value),
  });
  // 表格数据
  async function handleSearch() {
    const newData = await searchPlanByItemTypeZ(flowQueryData.value);
    inputTableData.value = newData.list;
    emit('updateArray', newData);
  }

  function resetCode() {
    scanDataList.value = [];
    scanCode.value = '';
  }

  // 重置
  function reset() {
    itemCode.value = '';
    qualityNumber.value = '';
    handleSearch();
  }

  // 标件扫码移交
  async function topToLastScan() {
    disabled.value = true;
    // const scannedItem = scanDataList.value.find(item => item.barcode === scanCode.value);
    // const info = ref({
    //   barCode: scannedItem.barcode,
    //   bzjCodeType: scannedItem.bzjCodeType,
    //   sendType: scanCodeType.value,
    //   pageParameter: computed(() => ({
    //     rows: 100,
    //     page: pageNumber.value,
    //   })),
    // });
    const info = ref({
      barCode: computed(() => scanCode.value),
      sendType: scanCodeType.value,
      pageParameter: computed(() => ({
        rows: 500,
        page: 1,
      })),
    });
    try {
      const data: any = await searchBZJCode(info.value);
      if (data.retCode === '200') {
        for (let i = 0; i < data.responseBody.result.length; i += 1) {
          scanDataList.value.push(data.responseBody.result[i]);
        }
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
        barcode.value = scanCode.value;
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
    } catch (error) {
      Notification.error({
        title: '失败',
        content: '请检查输入法是否为英文输入法或是否为正确标间条码',
        closable: true,
      });
    } finally {
      disabled.value = false;
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    }
  }
  const getUserJobNumber = ref<any>(getUserJob());
  // 扫码移交加输入框回车
  async function scanSubmit() {
    if (scanCode.value === '9005' || scanCode.value === '90059005') {
      if (scanDataList.value.length > 0) {
        if (isConfirm.value) {
          const datas = scanDataList.value.map((item) => ({
            itemCode: item.itemCode,
            deliveryQty: item.deliveryQty,
            barcode: item.barcode,
            aoNo: item.aoNo,
            ckBarcode: item.ckBarcode,
            wmsDeliveryPlanId: item.wmsDeliveryPlanId,
          }));
          const info = ref({
            data: datas,
          });
          disabled.value = true;
          booleanStore.toggleBool(0);
          try {
            const data: any = await bzjScanRecive(info.value);
            if (data.retCode === '200') {
              booleanStore.toggleBool(0);
              Notification.success({
                title: '成功',
                content: data.message,
                closable: true,
              });
              scanDataList.value = [];
              handleSearch();
            } else {
              booleanStore.toggleBool(0);
              Notification.error({
                title: '失败',
                content: data.message,
                closable: true,
              });
              handleSearch();
            }
          } catch (error) {
            booleanStore.toggleBool(0);
            Notification.error({
              title: '失败',
              content: '系统异常，调用接口错误',
              closable: true,
            });
            console.log(error);
          } finally {
            disabled.value = false;
            scanCode.value = '';
            nextTick(() => {
              scanInput.value.focus();
            });
            isConfirm.value = false;
          }
        } else {
          // scanCode.value = '';
          nextTick(() => {
            scanInput.value.focus();
          });
          isConfirm.value = true;
        }
      } else {
        Notification.warning({
          title: '提示',
          content: '请先扫标准件编码',
          closable: true,
        });
      }
    } else {
      const inputData = inputTableData.value.find(
        (item: any) => item.ckBarcode === scanCode.value
      );
      if (inputData && inputData.SEAL_DATE !== null) {
        const currentDate = new Date(); // 获取当前时间的时间戳
        const sealDateObj = new Date(inputData.SEAL_DATE); // 将油封为时间戳
        const diffTime = currentDate.getTime() - sealDateObj.getTime(); // 计算时间差（毫秒）
        const diffDays = diffTime / (1000 * 60 * 60 * 24); // 转换为天数
        if (diffDays > 0) {
          Notification.error({
            title: '提示',
            content: `图号${inputData.itemCode}油封期已超期`,
            closable: true,
          });
        } else if (diffDays > -90 && diffDays <= 0) {
          Notification.error({
            title: '提示',
            content: `图号${inputData.itemCode}油封期已临期`,
            closable: true,
          });
        }
      }

      for (let i = 0; i < scanDataList.value.length; i += 1) {
        if (scanDataList.value[i].barcode === scanCode.value) {
          Notification.warning({
            title: '提示',
            content: '请误重复扫码',
            closable: true,
          });
          return;
        }
      }
      await topToLastScan();
    }
  }

  onMounted(() => {
    nextTick(() => {
      scanInput.value.focus();
    });
    handleSearch();
  });
  // 监听分页
  watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
    if (booleanStore.num5 === 6) {
      pageNumber.value = booleanStore.pageNum;
      pageSize.value = booleanStore.pageSize;
      handleSearch();
    }
  });
  watch(
    () => booleanStore.update,
    () => {
      if (booleanStore.num6 === 4) handleSearch();
    }
  );
  watch(
    scanDataList,
    () => {
      if (scanDataList.value.length !== 0) {
        current.value = 2;
      } else {
        current.value = 1;
      }
      booleanStore.setList(scanDataList.value, 8);
    },
    { deep: true }
  );
</script>

<template>
  <!-- <a-card :header-style="hStyle">
    <template #title>
      <div class="font">流程进度</div>
    </template>
    <a-steps type="arrow" small changeable :current="current">
      <a-step :description="description">扫码移交</a-step>
      <a-step :description="description2">标准件接收</a-step>
    </a-steps>
  </a-card> -->
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">扫码操作</div>
    </template>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <div>
          <a-input
            ref="scanInput"
            v-model="scanCode"
            placeholder="请输入缓存箱/托盘码/条码"
            size="large"
            :disabled="disabled"
            @keyup.enter="scanSubmit"
          />
        </div>
      </a-col>
      <a-col :span="6">
        <a-button type="primary" size="large" @click="scanSubmit"
          >标件接收</a-button
        >
        <a-button class="btn-reset" size="large" @click="resetCode"
          >重置</a-button
        >
      </a-col>
      <a-col :span="6">
        <a-select v-model="scanCodeType" size="large">
          <a-option value="Y">直配</a-option>
          <a-option value="N">不直配</a-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        <div class="div-tips"
          >默认物料需要直配的话去其他界面操作，如果不直配要入库，请选择不直配</div
        >
      </a-col>
    </a-row>
  </a-card>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">已移交标准件列表</div>
    </template>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <div>
          <a-input
            v-model="itemCode"
            placeholder="图号"
            size="large"
            allow-clear
          />
        </div>
      </a-col>
      <a-col :span="6">
        <div>
          <a-input
            v-model="qualityNumber"
            placeholder="质量编号"
            size="large"
            allow-clear
          />
        </div>
      </a-col>
      <a-col :span="6">
        <a-button type="primary" size="large" @click="handleSearch"
          >查询</a-button
        >
        <a-button class="btn-reset" size="large" @click="reset"
          >重置搜索框</a-button
        >
      </a-col>
    </a-row>
  </a-card>
</template>

<style scoped>
  .margin-top {
    margin-top: 10px;
  }
  .btn-group {
    float: right;
    margin-top: 15px;
  }

  .btn-reset {
    margin-left: 10px;
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
  .div-tips {
    align-items: center;
    text-align: center;
    color: #999;
  }
</style>
